<?php

namespace app\common\service\we_chat;

use think\facade\Env;

/**
 * 微信小程序相关服务
 */
class AppletService
{
    /**
     * 通过code获取openid
     * @param string $code 微信小程序code
     * @return array
     */
    public static function getOpenid(string $code): array
    {
        $AppID = Env::get('wxApplet.AppID');
        $AppSecret = Env::get('wxApplet.AppSecret');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$AppID}&secret={$AppSecret}&js_code={$code}&grant_type=authorization_code";
        $data = httpGet($url);
        $data = json_decode($data, true);
        if (!isset($data['openid'])) {
            throw new \Exception('微信调用错误1');
        }
        return $data;
    }

    /**
     * 获取小程序AccessToken
     * @return array
     * @throws \Exception
     */
    public static function appletAccessToken(): array
    {
        $access_token = cache("applet_access_token");
        if (empty($access_token)) {
            $AppID = Env::get('enterpriseApplet.AppID');
            $AppSecret = Env::get('enterpriseApplet.AppSecret');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$AppID}&secret={$AppSecret}";
            $data = httpGet($url);
            $data = json_decode($data, true);
            if (!isset($data['access_token'])) {
                throw new \Exception('微信调用错误2');
            }
            $access_token = $data;
            cache("applet_access_token", $access_token, 7000);
        }
        return $access_token;
    }

}